#include "Value.h"
#include "DataType.h"

namespace duomai {
    namespace im {

        Value::Value () {
            setValue("", SQLITEWRAPPER_NULL);
        }

        Value::Value (string value, DataType type) {
            setValue(value, type);
        }

        void Value::setValue(string value, DataType type) {
            m_isNULL = true;
            m_Value.clear();
            m_DataType = type;

            if (value.size() != 0) {
                m_isNULL = false;
                m_Value = value;
                m_DataType = type;
            }
        }
        Value::~Value () {
            //TODO
        }

        bool Value::isNULL() {
            return m_isNULL;
        }

        string Value::toSQL(DataType type) {
            if (isNULL())
                return "null";
            if (type == SQLITEWRAPPER_TEXT)
                return "'" + quoteStr(asString()) + "'";
            if (type == SQLITEWRAPPER_INTEGER)
                return intToStr(asInteger());
            return asString();

        }

        string Value::toString() {
            if (m_isNULL) {
                return "NULL";
            }

            return m_Value;
        }


        int64_t Value::asInteger() {
	        if (isNULL())
		        return 0;
	        long long value = 0;
	        sscanf(m_Value.c_str(),"%lld",&value);
	        return value;
        }

        double Value::asDouble() {
	        if (isNULL())
		        return 0.0;

	        double value = 0;
	        sscanf(m_Value.c_str(),"%lf",&value);
	        return value;
        }


        string Value::asString()
        {
	        return m_Value;
        }

        string Value::intToStr(int value) {
	        char buffer[32];
	        sprintf(buffer,"%d",value);
	        return buffer;
        }


        string Value::intToStr(int64_t value)
        {
	        char buffer[64];
	        sprintf(buffer,"%lld",value);
	        return buffer;
        }
        string Value::quoteStr(string value)
        {
	        string s;
	        for (string::iterator it = value.begin(); it != value.end(); it++)
	        {
		        char c = *it;
		        s += c;
		        if (c == '\'')
			        s += c;
	        }
	        return s;
        }
    } /* im */ 

} /* duomai  */ 

